package com.ironman.sailboat.mobile.listener;

import cn.hutool.json.JSONUtil;
import com.ironman.sailboat.mobile.context.MockConfigContext;
import com.ironman.sailboat.mobile.dataobject.mysql.MockConfig;
import com.ironman.sailboat.mobile.properties.SysTrainingProperties;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row;
import com.mybatisflex.core.row.RowUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class AppReadyEventListener implements ApplicationListener<ApplicationStartedEvent> {

    final SysTrainingProperties sysTrainingProperties;

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        try {
            DataSourceKey.use("mysql");
            Row row = Db.selectOneById("mock_config", "mock_code", sysTrainingProperties.getMockCode());
            if (row != null) {
                MockConfig mockConfig = RowUtil.toEntity(row, MockConfig.class);
                log.info("mockConfig: {}", JSONUtil.toJsonPrettyStr(mockConfig));
                MockConfigContext mockConfigContext = new MockConfigContext(
                        mockConfig.getFromTrainingBoatCode(),
                        mockConfig.getFromTenantCode(),
                        mockConfig.getFromLevelId(),
                        mockConfig.getFromMHmId(),
                        mockConfig.getToTenantCode(),
                        mockConfig.getToLevelId(),
                        mockConfig.getToMHmId(),
                        mockConfig.getToMHmName(),
                        mockConfig.getToColor()
                );
                MockConfigContext.singleton(mockConfigContext);
            }
        } finally {
            DataSourceKey.clear();
        }
    }
}